package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private OrderTccAction orderTccAction;
    //第一个开启全局事务
    @GlobalTransactional
    @Override
    public void create(Order order) {
        //远程调用发号器生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        // 临时随机生成一个id,添加发号器后这行代码删除
        order.setId(orderId);
        //不再直接执行业务操作储存订单，
        // 而是改成调用 TCC第一阶段方法，冻结订单、预留订单
        /*
        * orderTccAction 是一个动态代理对象，用AOP添加了通知代码，
        * 在通知代码中，创建了上下文对象，并传递到被代理的目标方法中
        * */
        orderTccAction.prepare(null,
                    order.getId(),
                    order.getUserId(),
                    order.getProductId(),
                    order.getCount(),
                    order.getMoney());
//        orderMapper.create(order);

        // 调用库存减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 调用账户减少账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }

}
